package com.ule.merchant.order.mon.service.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class OkhttpUtil {
	private static Logger logger = LoggerFactory.getLogger(OkhttpUtil.class);
	OkhttpUtil(){}
	private static String timestampName = "timestamp";
	private static String nonceName = "nonce";
	private static String contentType = "application/json;charset=utf-8";
	private  static final int CONNECT_TIMEOUT = 60;
	private static final  int READ_TIMEOUT = 120;
	private static final  int WRITE_TIMEOUT = 60;

    private static OkHttpClient client = new OkHttpClient.Builder()
			.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
			.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
			.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
			.build();

	private static Map<String, String> assembleHeaders(Map<String, String> headersMap) {
		if(headersMap == null ){
			headersMap = new HashMap<>();
		}
		HttpServletRequest request = null;
		try {
			if(RequestContextHolder.getRequestAttributes() != null)
				request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		}catch (Exception e){
			logger.error(e.getMessage());
		}
		if(request != null && request.getHeader("traceId") != null)
			headersMap.put("traceId",request.getHeader("traceId"));
		else{
			String traceId = IpUtil.getTraceId();
			MDC.put("traceId",traceId);
			headersMap.put("traceId",traceId);
		}
		if(headersMap.get("traceId") != null)
			headersMap.put(nonceName, headersMap.get("traceId"));
		headersMap.put(timestampName,System.currentTimeMillis()+"");
		if(System.getProperty("ule.app") != null)
			headersMap.put("client",System.getProperty("ule.app"));
		if(System.getProperty("ule.module") != null)
			headersMap.put("module", System.getProperty("ule.module"));
		headersMap.put("Connection", "close");
		return headersMap;
	}

	public static String postJson(String url,Map<String,Object> params,Map<String,String> headersMap) {
		RequestBody body = RequestBody.create(MediaType.parse(contentType), JSONObject.toJSONString(params));
		Request.Builder b = new Request.Builder().url(url).post(body);
		headersMap =assembleHeaders(headersMap);
		Iterator<String> iterator = headersMap.keySet().iterator();
		while (iterator.hasNext()){
			String k = iterator.next();
			b.addHeader(k, headersMap.get(k));
		}
		Headers hraders = Headers.of(headersMap);
		Request request = b.headers(hraders).build();
		try {
			Response response = client.newCall(request).execute();
			if(response.isSuccessful()){
				String string = response.body().string();
				return string;
			}
			logger.info("http response = {}",response.body());
		}catch (Exception e){
			throw new RuntimeException(e);
		}
		return null;
	}

	//如果需要返回String：result.get("body").toString()
	public static Map<String,Object> postFormAndHeaders(String url,Map<String,String> params,Map<String,String> headersMap){
		headersMap =assembleHeaders(headersMap);
		FormBody.Builder bulider = new FormBody.Builder();
		if(params != null){
			Iterator<String> iterator = params.keySet().iterator();
			while (iterator.hasNext()){
				String k = iterator.next();
				bulider.add(k, params.get(k));
			}
		}
		Headers headers = Headers.of(headersMap);
		RequestBody body = bulider.build();
		Request request = new Request.Builder().url(url).post(body).headers(headers).build();
		Map<String,Object> result = new HashMap<>();
		result.put("body","");
		try{
			Response response = client.newCall(request).execute();
			if(response.isSuccessful()){
				// 获取返回数据的头部信息
				Map<String, List<String>> resHeaders = response.headers().toMultimap();//.get("set-cookie");//.namesAndValues
				String string = response.body().string();
				result.put("body",string);
				result.put("headers",resHeaders);
				return result;
			}
			logger.info("http response = {}",response.body());
		}catch (Exception e){
			throw new RuntimeException(e);
		}
		return result;
	}

}
